package zunge.twitterdel.bean;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

public class RepostTweetDAO {
	private BeanFactory<TweetPairDistinct> factory;
	private BeanTable<TweetPairDistinct> tweetTable;
	
	static String jdbcDriver = "com.mysql.jdbc.Driver";
	
	public RepostTweetDAO(String jdbcURL, String userName, String password) throws DAOException {
		try{
			
	        tweetTable = BeanTable.getSQLInstance(TweetPairDistinct.class,"reposttweets",
	        									jdbcDriver, jdbcURL, userName, password);
	        if (!tweetTable.exists()) tweetTable.create("oldTweetID");
	        
	        tweetTable.setIdleConnectionCleanup(true);
	        factory = tweetTable.getFactory();
	        
		}catch (BeanFactoryException e) {throw new DAOException(e);}
	}
	
	public void create(TweetPairDistinct tweetPairDistinct) throws DAOException{
		try{
			
			Transaction.begin();
			TweetPairDistinct tweetPairDB = factory.create(tweetPairDistinct.getOldTweetID());
			factory.copyInto(tweetPairDistinct, tweetPairDB);
			Transaction.commit();
			
		}catch(RollbackException e){throw new DAOException(e);
		}finally{
			if(Transaction.isActive()){
				Transaction.rollback();
			}
		}
	}
}
